'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2 } from 'lucide-react'
import ReactECharts from 'echarts-for-react'

interface StepData {
  timestamp: number
  steps: number
  calories: number
  distance: number
}

interface StepChartProps {
  userId: string
  selectedDate: string
}

export function StepChart({ userId, selectedDate }: StepChartProps) {
  const [stepData, setStepData] = useState<StepData[]>([])
  const [loading, setLoading] = useState(false)

  // 获取步数数据
  const fetchStepData = async () => {
    try {
      // 数据库中的时间戳是本地时间戳，直接构造本地时间范围
      const selectedDateObj = new Date(selectedDate)
      
      // 构造本地时间的开始和结束时间戳
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)
      
      console.log('步数查询时间范围:', {
        selectedDate,
        startDate: startDate.toLocaleString('zh-CN'),
        endDate: endDate.toLocaleString('zh-CN'),
        startDateISO: startDate.toISOString(),
        endDateISO: endDate.toISOString(),
        startTimestamp: startDate.getTime(),
        endTimestamp: endDate.getTime()
      })

      const response = await fetch(`/api/health?userId=${userId}&dataType=step&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      
      if (!response.ok) {
        throw new Error('Failed to fetch step data')
      }

      const data = await response.json()
      console.log('步数 API响应:', data)

      // 提取步数数据
      const logs = data.data?.logs || data.logs || []
      console.log('步数 提取的logs:', {
        logsLength: logs.length,
        firstLog: logs[0] || null,
        lastLog: logs[logs.length - 1] || null
      })

      const processedData = processStepData(logs)
      console.log('处理后的步数数据:', {
        originalLogsCount: logs.length,
        processedDataCount: processedData.length,
        firstProcessedData: processedData[0] || null,
        lastProcessedData: processedData[processedData.length - 1] || null
      })
      setStepData(processedData)
    } catch (error) {
      console.error('获取步数数据失败:', error)
      setStepData([])
    }
  }

  // 处理步数数据
  const processStepData = (logs: any[]): StepData[] => {
    const stepPoints: StepData[] = []
    
    logs.forEach((log) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      // 只使用detailMinterStep作为单个数据点处理，避免与arraySteps重复统计
      if (logData.detailMinterStep) {
        let timestamp = parseInt(logData.ts) || parseInt(log.timestamp)
        
        if (timestamp < 10000000000) {
          timestamp = timestamp * 1000
        }
        
        const minValidTimestamp = new Date('2020-01-01').getTime()
        const maxValidTimestamp = new Date('2070-12-31').getTime()
        
        if (timestamp >= minValidTimestamp && timestamp <= maxValidTimestamp) {
          const stepCount = parseInt(logData.detailMinterStep) || 0
          if (stepCount > 0) {
            stepPoints.push({
              timestamp,
              steps: stepCount,
              calories: parseFloat(logData.calories) || 0,
              distance: parseFloat(logData.distance) || 0
            })
          }
        }
      }
    })

    return stepPoints.sort((a, b) => a.timestamp - b.timestamp)
  }

  // 生成步数图表配置
  const generateStepChart = () => {
    if (stepData.length === 0) return null

    // 按2小时聚合数据
    const hourlyData = new Map<string, { steps: number; calories: number; distance: number }>()

    // 从实际数据中获取日期范围，如果有数据则使用数据的日期，否则使用selectedDate
    let dayStart: Date
    
    if (stepData.length > 0) {
      // 使用实际数据的第一个时间戳来确定日期（本地时间）
      const firstDataDate = new Date(stepData[0].timestamp)
      dayStart = new Date(firstDataDate.getFullYear(), firstDataDate.getMonth(), firstDataDate.getDate())
    } else {
      // 如果没有数据，使用 selectedDate 的本地零点作为基准
      const selectedDateObj = new Date(selectedDate)
      dayStart = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate())
    }

    // 初始化12个2小时时段的数据结构（0-2, 2-4, 4-6, ..., 22-24）
    for (let period = 0; period < 12; period++) {
      const startHour = period * 2
      const periodKey = `${startHour.toString().padStart(2, '0')}:00-${(startHour + 2).toString().padStart(2, '0')}:00`
      hourlyData.set(periodKey, { steps: 0, calories: 0, distance: 0 })
    }

    // 聚合步数数据到对应2小时时段
    stepData.forEach(data => {
      const dataDate = new Date(data.timestamp)
      // 使用本地时间获取小时
      const hour = dataDate.getHours()
      const period = Math.floor(hour / 2) // 确定属于哪个2小时时段
      const startHour = period * 2
      const periodKey = `${startHour.toString().padStart(2, '0')}:00-${(startHour + 2).toString().padStart(2, '0')}:00`
      
      if (hourlyData.has(periodKey)) {
        const periodData = hourlyData.get(periodKey)!
        periodData.steps += data.steps
        periodData.calories += data.calories
        periodData.distance += data.distance
      }
    })

    // 计算全天步数的最大值用于Y轴范围
    const allSteps = Array.from(hourlyData.values()).map(d => d.steps)
    const maxSteps = Math.max(...allSteps, 100) // 至少100步作为最小范围

    // 准备图表数据
    const xAxisData: string[] = []
    const seriesData: number[] = []

    // 生成12个2小时时段的数据
    for (let period = 0; period < 12; period++) {
      const startHour = period * 2
      const periodLabel = `${startHour.toString().padStart(2, '0')}:00`
      const periodKey = `${startHour.toString().padStart(2, '0')}:00-${(startHour + 2).toString().padStart(2, '0')}:00`
      
      xAxisData.push(periodLabel)
      const periodData = hourlyData.get(periodKey)
      seriesData.push(periodData ? periodData.steps : 0)
    }

    return {
      title: {
        text: '步数分析',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (params && params.length > 0) {
            const data = params[0]
            const periodIndex = data.dataIndex
            const startHour = periodIndex * 2
            const endHour = startHour + 2
            const periodKey = `${startHour.toString().padStart(2, '0')}:00-${endHour.toString().padStart(2, '0')}:00`
            const periodData = hourlyData.get(periodKey)
            
            // 构建显示时间
            let displayDateTime: string
            if (stepData.length > 0) {
              const firstDataDate = new Date(stepData[0].timestamp)
              const displayDate = new Date(firstDataDate.getFullYear(), firstDataDate.getMonth(), firstDataDate.getDate(), startHour, 0, 0)
              displayDateTime = displayDate.toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
              })
            } else {
              const selectedDateObj = new Date(selectedDate)
              const displayDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), startHour, 0, 0)
              displayDateTime = displayDate.toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
              })
            }

            if (!periodData || periodData.steps === 0) {
              return `${displayDateTime} - ${endHour.toString().padStart(2, '0')}:00<br/>无步数数据`
            }
            
            return `${displayDateTime} - ${endHour.toString().padStart(2, '0')}:00<br/>步数: ${periodData.steps}步<br/>距离: ${periodData.distance.toFixed(2)}km<br/>卡路里: ${periodData.calories.toFixed(1)}千卡`
          }
          return ''
        }
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLabel: {
          interval: 0, // 显示所有标签
          rotate: 0
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        name: '步数',
        min: 0,
        max: Math.ceil(maxSteps / 100) * 100, // 向上取整到百位
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [{
        name: '步数',
        type: 'bar',
        data: seriesData,
        itemStyle: {
          color: '#fbbf24', // 黄色
          borderRadius: [4, 4, 0, 0] // 顶部圆角
        },
        barWidth: '60%'
      }]
    }
  }

  // 获取统计信息
  const getStatistics = () => {
    if (stepData.length === 0) {
      return {
        title: '步数统计',
        stats: [
          { label: '总步数', value: '0' },
          { label: '总距离', value: '0.00 km' },
          { label: '总卡路里', value: '0.0 千卡' },
          { label: '数据点', value: '0' }
        ]
      }
    }

    const totalSteps = stepData.reduce((sum, d) => sum + d.steps, 0)
    const totalDistance = stepData.reduce((sum, d) => sum + d.distance, 0)
    const totalCalories = stepData.reduce((sum, d) => sum + d.calories, 0)

    return {
      title: '步数统计',
      stats: [
        { label: '总步数', value: totalSteps.toString() },
        { label: '总距离', value: `${totalDistance.toFixed(2)} km` },
        { label: '总卡路里', value: `${totalCalories.toFixed(1)} 千卡` },
        { label: '数据点', value: stepData.length.toString() }
      ]
    }
  }

  // 数据获取
  useEffect(() => {
    if (!userId || !selectedDate) return

    setLoading(true)
    
    const fetchData = async () => {
      await fetchStepData()
      setLoading(false)
    }

    fetchData()
  }, [userId, selectedDate])

  const statistics = getStatistics()
  const chartConfig = generateStepChart()

  return (
    <div className="space-y-4">
      {/* 图表区域 */}
      <Card>
        <CardHeader>
          <CardTitle>步数分析</CardTitle>
          <CardDescription>
            显示全天的步数数据，按2小时时段聚合显示步数、距离和卡路里消耗
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">加载中...</span>
            </div>
          ) : chartConfig ? (
            <ReactECharts
              option={chartConfig}
              style={{ width: '100%', height: '400px' }}
              opts={{ renderer: 'canvas' }}
            />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              <div className="text-center">
                <p className="text-lg font-medium">暂无数据</p>
                <p className="text-sm">该日期没有步数数据</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>{statistics.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {statistics.stats.map((stat, index) => (
              <div key={index} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="text-2xl font-bold text-gray-900">{stat.value}</div>
                <div className="text-sm text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
